package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@ResponseBody
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录时，校验验证码是否正确
     *
     * @param param 包括用户手机号和验证码
     * @return 登录成功和失败返回不同的结果
     */
    @PostMapping("/loginVerification")
    public ResponseEntity<Object> loginVerification(@RequestBody Map<String, String> param) {
        try {
            String phone = param.get("phone");
            String code = param.get("verificationCode");

            String data = this.userService.loginVerification(phone, code);

            //登录成功
            if (StringUtils.isNotEmpty(data)) {
                String[] split = StringUtils.split(data, "|");

                Map<String, Object> map = new HashMap<>(2);
                map.put("token", split[0]);
                map.put("isNew", Boolean.valueOf(split[1]));
                return ResponseEntity.ok(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    @GetMapping("/{token}")
    private User queryUserByToken(@PathVariable("token") String token) {
        User user = null;
        try {
            return userService.queryUserByToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
